package impl

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/viper"
	"reflect"
	"strconv"
	"time"
	"yanwc.gokit/user_svc/common"
	"yanwc.gokit/user_svc/models"
	"yanwc.gokit/user_svc/service"
)

func init() {
	viper.AddConfigPath("../config")

}

type LoginServiceImpl struct {
}

func (l LoginServiceImpl) Login(name, password string, loginType models.LoginType, subSystemId int) (*service.LoginResult, error) {
	var account models.Account
	var user models.User
	err := models.Db.Where("login_name=? and sub_system_id=? and login_type=?", name, subSystemId, loginType).First(&account).Error
	if err != nil {
		return nil, err
	}
	if reflect.DeepEqual(account, models.Account{}) {
		return nil, errors.New("用户不存在")
	}
	var pwd = common.Md5(password)
	models.Db.Where("id=?", account.UserId).Preload("Roles", "sub_system_id=?", strconv.Itoa(int(account.SubSystemId))).Preload("Roles.Codes").First(&user)
	var codes []string
	for _, role := range user.Roles {
		for _, code := range role.Codes {
			codes = append(codes, code.Code)
		}
	}
	claim := jwt.MapClaims{
		"id":          user.ID,
		"accountId":   account.ID,
		"loginName":   account.LoginName,
		"subSystemId": account.SubSystemId,
		"nbf":         time.Now().Unix(),
		"iat":         time.Now().Unix(),
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenStr, err := token.SignedString([]byte(viper.GetString("token_secret")))
	if err != nil {
		return nil, err
	}
	if account.Password == pwd {
		return &service.LoginResult{
			UserId:    account.User.ID,
			AccountId: account.ID,
			UserName:  user.Name,
			NickName:  user.NickName,
			Avatar:    user.Avatar,
			LoginName: account.LoginName,
			Codes:     codes,
			Token:     tokenStr,
		}, nil
	}
	return nil, nil
}

//用户名和密码登录
func (l LoginServiceImpl) LoginByUserNameAndPassword(name, password string) (*service.LoginResult, error) {
	return l.Login(name, password, models.UserNameAndPassword, 0)
}
